package com.hanxiaozhang.advanced.no2return;

import com.rabbitmq.client.*;
import org.springframework.amqp.core.ExchangeTypes;

import java.io.IOException;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2022/9/24
 * @since 1.0.0
 */
public class Consumer {

    private static final String EXCHANGE_NAME = "return_exchange";

    /**
     * 路由的key
     */
    private static final String ROUTING_KEY = "return.#";

    /**
     * 绑定的队列
     */
    private static final String QUEUE_NAME = "return_queue";

    public static void main(String[] args) throws Exception {

        // 创建链接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置RabbitMQ所在主机ip或者主机名
        factory.setHost("localhost");
        // 创建一个连接
        Connection connection = factory.newConnection();
        // 创建一个频道
        Channel channel = connection.createChannel();

        // 声明队列
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        // 声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME, ExchangeTypes.TOPIC);
        // 绑定
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);
        System.out.println("Waiting for messages.");

        // 声明消费者
        com.rabbitmq.client.Consumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Received '" + message + "'");
            }
        };
        // 进行消费的绑定
        channel.basicConsume(QUEUE_NAME, true, defaultConsumer);
    }

}
